package com.tensquare.user.controller;

import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import util.IdWorker;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author Alfred
 * @description TODO
 * @date 2021/4/28 18:08
 */
@RequestMapping("/user")
@CrossOrigin
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JwtUtil jwtUtil;


    /**
     * fetch data by rule id
     *
     * @description  发送短信验证码
     * @param
     * @return
     */
    @PostMapping("/sendsms/{mobile}")
    public Result sendsms(@PathVariable String mobile){
        userService.sendSms(mobile);
        return new Result(true, StatusCode.OK,"发送成功");
    }

    /**
     * fetch data by rule id
     *
     * @description  用户注册
     * @param
     * @return
     */
    @PostMapping("/register/{code}")
    public Result register(@RequestBody User user,@PathVariable String code){
        userService.add(user,code);
        return new Result(true,StatusCode.OK,"注册成功");
    }

    /**
     * 用户登陆
     * @param mobile
     * @param password
     * @return
     */
    @RequestMapping(value="/login",method=RequestMethod.POST)
    public Result login(String mobile,String password){
        User user = userService.findByMobileAndPassword(mobile,password);
        if(user!=null){
            return new Result(true,StatusCode.OK,"登陆成功");
        }else{
            //登录成功生成令牌
            String token = jwtUtil.createJWT(user.getId(), user.getMobile(), "user");
            return new Result(false,StatusCode.LOGINERROR,"用户名或密码错误",token);
        }
    }

    /**
     * fetch data by rule id
     *
     * @description  删除
     * @param
     * @return
     */
    @RequestMapping(value="/{id}",method= RequestMethod.DELETE)
    public Result delete(@PathVariable String id ){
        Claims claims=(Claims) request.getAttribute("admin_claims");
        if(claims==null){
            return new Result(true,StatusCode.ACCESSERROR,"无权访问");
        }
        userService.deleteById(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }
}
